<template>
  <div class="table">
    <div class="container">
      <div class="handle-box">
        <el-input v-model="search_word" size="mini" placeholder="请输入搜索歌名" class="handle-input">
        </el-input>
        <el-button type="primary" @click="dialogVisible = true">添加歌手</el-button>
        <el-button type="danger" @click="deleteMoreButton">批量删除</el-button>
      </div>
      <el-dialog title="添加歌手" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="歌名" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="专辑" prop="introduction">
            <el-input v-model="ruleForm.introduction"></el-input>
          </el-form-item>
          <el-form-item label="歌词" prop="lyric">
            <el-input type="textarea" v-model="ruleForm.lyric"></el-input>
          </el-form-item>
          <el-form-item label="歌曲文件" prop="file">
            <input type="file" @change="getFile($event,'file')">
            <!-- <el-input type="file" v-model="ruleForm.file" accept=".mp4"></el-input> -->
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addSong($event)">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="修改歌手" :visible.sync="editVisible" width="30%" :before-close="handleClose">
        <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="歌名" prop="name">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="专辑" prop="introduction">
            <el-input v-model="editForm.introduction"></el-input>
          </el-form-item>
          <el-form-item label="歌词" prop="lyric">
            <el-input type="textarea" v-model="editForm.lyric"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editSong($event)">确 定</el-button>
        </span>
      </el-dialog>
      <el-table border :data="this.data" ref="multipleTable" border style="width: 100%" height="630px"
        @selection-change="deleteMore">
        <el-table-column width="30px" type="selection"></el-table-column>
        <el-table-column align="center" label="图片" width="180">
          <template slot-scope="scope">
            <div class="song-img">
              <img :src="getUrl(scope.row.pic)" alt="图片" style="width: 100%;">
            </div>

            <div class="play" @click="setSongUrl(scope.row.url, scope.row.name)">
              <div v-if="toggle !== scope.row.name ">

                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-bofanganniu"></use>
                </svg>

              </div>
              <div v-if="toggle === scope.row.name ">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-zanting"></use>
                </svg>

              </div>
            </div>

          </template>
        </el-table-column>
        <el-table-column align="center" label="歌名" width="120px">
          <template slot-scope="scope">
            {{scope.row.name}}
          </template>
        </el-table-column>
        </el-table-column>
        <el-table-column align="center" label="专辑" width="120px">
          <template slot-scope="scope" size="mini">
            {{scope.row.introduction}}
          </template>
        </el-table-column>
        </el-table-column>
        <el-table-column align="center" label="更新时间" width="120px">
          <template slot-scope="scope">
            {{attachBirth(scope.row.updateTime)}}
          </template>
        </el-table-column>

        <el-table-column align="center" label="歌词" width="500px">
          <template slot-scope="scope">
            <ul style="height: 100px; overflow: scroll">
              <li>
              <li v-for="item in parseLyric(scope.row.lyric)">
                {{ item}}
              </li>
            </ul>
          </template>
        </el-table-column>
        </el-table-column>
        <el-table-column label="更新资源" align="center" width="110px">
          <template slot-scope="scope" align="center">
            <el-upload class="upload-demo" :action="uploadPic(scope.row.id)" :show-file-list="false" :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <el-button type="success," size="mini">更新图片</el-button>
            </el-upload>
            <el-upload class="upload-demo" :action="uploadUrl(scope.row.id)" :show-file-list="false" :on-success="handleSongSuccess"
              :before-upload="beforeSongUpload">
              <el-button type="success," size="mini">更新图片</el-button>
            </el-upload>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="100px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="editSongButton(scope.row)">修改</el-button>
            <el-button type="danger" size="mini" @click="delSongButton(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
      <div class="pagination">
        <el-pagination align="center" @current-change="handleCurrentChange" background layout="total, prev, pager, next"
          :current-page="currentPage" :page-size="pageSize" :total="tableData.length">
        </el-pagination>
      </div>
    </div>

  </div>
</template>

<script>
  import songAudio from '../components/songAudio'
  import {
    mixin
  } from '../mixins'
  import {
    mapGetters
  } from 'vuex'
  import '@/assets/js/iconfont.js'
  export default {
    mixins: [mixin],
    name: 'songPage',
    data() {
      return {
        toggle: '',
        search_word: '',
        multipleSelect: [],
        dialogVisible: false,
        editVisible: false,
        currentPage: 1,
        pageSize: 5,
        delSongId: -1,
        formData: new FormData(),
        ruleForm: {
          singerId: this.$route.query.singerId,
          name: '',
          introduction: '',
          file: '',
          lyric: ''

        },
        editForm: {
          id: '',
          name: '',
          introduction: '',
          lyric: '',
        },
        tableData: [],
        tempData: [],
        rules: {
          name: [{
            required: true,
            message: '请输入歌曲名称',
            trigger: 'blur'
          }],
          introduction: [{
            required: true,
            message: '请输入专辑',
            trigger: 'blur'
          }],
          file: [{
            required: true,
            message: '请选择上传文件',
            trigger: 'blur'
          }],
          lyric: [{
            required: false,
            message: '请输入歌词',
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.getData();
    },
    destroyed() {
      this.$store.commit('setIsPlay', false)
    },
    computed: {
      ...mapGetters([
        'isPlay' // 播放状态
      ]),
      // 计算当前表格中的数据
      data() {
        return this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
      }
    },
    watch: {
      search_word: function() {
        if (this.search_word == '') {
          this.tableData = this.tempData;
        } else {
          this.tableData = [];
          for (let item of this.tempData) {
            if (item.name.includes(this.search_word)) {
              this.tableData.push(item);
            }
          }
        }
        this.currentPage = 1;
      }
    },
    methods: {
      setSongUrl(url, name) {
        this.$store.commit('setUrl', this.$store.state.HOST + url)
        this.toggle = name
        if (this.isPlay) {
          this.$store.commit('setIsPlay', false)
        } else {
          this.$store.commit('setIsPlay', true)
        }
        if (this.isPlay === false) {
          this.toggle = '';
        }
      },
      parseLyric(text) {
        let lines = text.split('\n')
        let pattern = /\[\d{2}:\d{2}.(\d{3}|\d{2})\]/g
        let result = []

        // 对于歌词格式不对的特殊处理
        if (!(/\[.+\]/.test(text))) {
          return [text]
        }
        for (let item of lines) {
          if (pattern.test(item)) {
            let value = item.replace(pattern, '') // 存歌词
            result.push(value)
          }
        }
        return result
      },
      editSong() {
        let data = {
          "id": this.editForm.id,
          "name": this.editForm.name,
          "introduction": this.editForm.introduction,
          "lyric": this.editForm.lyric
        };
        this.axios.post(this.$store.state.HOST + '/song/update', data).then((res) => {
          if (res.data.code == 1) {
            this.$message.success("修改成功");
            this.getData();
            this.editVisible = false;
          } else {
            this.$message.error("修改失败")
          }
        })
      },
      editSongButton(row) {
        this.editForm.id = row.id;
        this.editForm.name = row.name;
        this.editForm.introduction = row.introduction;
        this.editForm.lyric = row.lyric;
        this.editVisible = true;
      },
      deleteMore(more) {
        this.multipleSelect = more;
      },
      deleteMoreButton() {
        if (confirm("删除之后不可恢复，你确定要批量删除！")) {
          let ids = [];
          for (let item of this.multipleSelect) {
            ids.push(item.id);
          }
          let delData = {
            "ids": ids
          }
          this.axios.post(this.$store.state.HOST + '/song/delete', delData, {}).then((res) => {
            if (res.data.code == 1) {
              this.$message.success("批量删除成功");
              this.getData();
            } else {
              this.$message.error("批量删除失败");
            }
          })
        }
      },
      delSongButton(id) {
        this.delSongId = id;
        let ids = [];
        ids.push(this.delSongId);
        let delData = {
          'ids': ids
        }
        if (confirm("删除之后不可恢复，你确定要删除它！")) {
          this.axios.post(this.$store.state.HOST + '/song/delete', delData, {}).then((res) => {
            if (res.data.code == 1) {
              this.$message.success("删除成功");
              this.getData();
            } else {
              this.$message.error("删除失败");
            }
          })
        }
      },
      uploadPic(songId) {
        return this.$store.state.HOST + '/song/updateSongPic?id=' + songId;
      },
      uploadUrl(songId) {
        return this.$store.state.HOST + '/song/updateSongUrl?id=' + songId;
      },
      handleCurrentChange(page) {
        this.currentPage = page;
      },
      getData() {
        this.axios.get(this.$store.state.HOST + '/song/findBySingerId', {
          params: {
            'singerId': this.ruleForm.singerId
          }
        }).then((res) => {
          if (res.data.code == 1) {
            this.tableData = res.data.data;
            this.tempData = res.data.data;
          }
        })
      },
      getUrl(pic) {
        return this.$store.state.HOST + pic;
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      getFile(event, input_file_name) {
        this.formData.append(input_file_name, event.target.files[0]);
      },
      addSong() {
        if (this.ruleForm.lyric == '') {
          this.ruleForm.lyric = '[00:00:00]暂无歌词';
        };
        this.ruleForm.name = this.$route.query.singerName + '-' + this.ruleForm.name;
        for (let i in this.ruleForm) {
          this.formData.append(i, this.ruleForm[i]);
        }

        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        };
        this.axios.post('http://localhost:8888/music/song/add', this.formData, config).then((res) => {
          if (res.data.code == 1) {
            this.$notify({
              title: res.data.description,
              message: this.ruleForm.name + "添加成功",
              type: 'success'
            });
            this.dialogVisible = false;
            this.getData();

          }
          if (res.data.code == 0) {
            this.$notify.error({
              title: res.data.description,
              message: this.ruleForm.name + "添加失败",
            });
          }
        })
      },

    }
  }
</script>

<style>
  .handle-box {
    margin-bottom: 5px;
  }

  .song-img {
    width: 100%;
    height: 80px;
    border-radius: 5px;
    margin-bottom: 5px;
    overflow: hidden;
  }

  .handle-input {
    width: 300px;
    display: inline-block;
  }

  .play {
    position: absolute;
    z-index: 100;
    width: 80px;
    height: 80px;
    top: 18px;
    left: 45px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }

  .icon {
    width: 2em;
    height: 2em;
    color: white;
    fill: currentColor;
    overflow: hidden;
  }

  .pagination {
    display: flex;
    justify-content: center;
  }
</style>
